package com.example.admin.interceptor;

import cn.hutool.core.text.AntPathMatcher;
import com.alibaba.fastjson.JSONObject;
import com.example.admin.bean.LoginUserDetails;
import com.example.admin.constants.RedisKeyConstants;
import com.example.admin.utils.JwtUtil;
import com.example.admin.utils.StringUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.AuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.access.intercept.RequestAuthorizationContext;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
@Component
public class TokenAuthrizationManager implements AuthorizationManager<RequestAuthorizationContext> {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Value("${zhyl.securet}")
    private String securitykey;
    @Value("${zhyl.expire}")
    private int dataoffset;
    @Override
    public AuthorizationDecision check(Supplier<Authentication> authentication, RequestAuthorizationContext context) {
        String uuid = context.getRequest().getHeader("token");
        if (StringUtils.isEmpty(uuid)){
//            恶意传入token
            return new AuthorizationDecision(false);
        }
//        用用户传入的uuid获取token
        String token = stringRedisTemplate.opsForValue().get(RedisKeyConstants.LOGIN_USER_TOKEN + uuid);
        if(StringUtils.isEmpty(token)){
//            token过期
//            恶意传入uuid
            return new AuthorizationDecision(false);
        }
        Claims claims = JwtUtil.parseJWT(securitykey,token);
        String user = (String)claims.get("user");
        LoginUserDetails loginUserDetails = JSONObject.parseObject(user, LoginUserDetails.class);

//        uuid续命
        stringRedisTemplate.opsForValue().set(RedisKeyConstants.LOGIN_USER_UUID+loginUserDetails.getUsername(),uuid,dataoffset, TimeUnit.SECONDS);
//        token续命
        stringRedisTemplate.opsForValue().set(RedisKeyConstants.LOGIN_USER_TOKEN+uuid,token,dataoffset,TimeUnit.SECONDS);

        //验证用户是否拥有资源
        String uri = context.getRequest().getRequestURI();
// 从第 5 个字符开始截取（"/api" 长度为 4 ），去掉 /api 前缀
        if (uri.startsWith("/api")) {
            uri = uri.substring(4);
        }
        String method = context.getRequest().getMethod();
        String finalurl = method + "" + uri;
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String path : loginUserDetails.getResourceRequestPaths()) {
            if (antPathMatcher.match(path,finalurl)){
                System.out.println("有权限访问资源：" + finalurl+"--------------------");
                return new AuthorizationDecision(true);
            }
        }

        return new AuthorizationDecision(false);
    }
}
